/**
 * 应用主页处理器，依赖app.js
 */
$(function() {
    emplmis.app.start();	//	启动应用
	easyloader.locale = 'zh_CN';	//	easyui本地化语言设置：中文
	$('#appName').append('<span>'+ _appConfigs.appName +'</span>');	//	设置系统名称
	_appConfigs.appLoginName = $('#indexLoginName').val();	//	设置用户登录名
	var data = _appConfigs.getUserData();
	$('#appUserName').append(data.name?data.name:"");	//	设置系统用户名称
	$('#appUserLastVisit').append(data.lastVisit1?data.lastVisit1:"");	//	设置上次访问时间
	getDicts();  //加载字典表数据
	window.mainpage.loadResources();	//	加载资源菜单
	window.mainpage.bindMainTabsButtonEvent();	//	 绑定标签栏按钮事件
	window.mainpage.bindToolbarButtonEvent();	//	绑定工具栏按钮事件
});

var mainLayout = "#indexMainLayout", mainTabs = "#indexMainTabs", mainTabsToggleAll = "#indexMainTabsToggleAll", mainTabsToggleAllIcon = "#indexMainTabsToggleAllIcon",
	menuExit = "#menuAppExit", menuFullSreen = "#indexFullScreen", menuIndexScreenMask = "#menuIndexScreenMask";

window.mainpage = {	//	新建命名空间mainpage
	isCollapse: false,
	bindMainTabsButtonEvent: function() {	//	绑定标签栏按钮事件
		$(mainTabsToggleAll).click(function () { window.mainpage.togglePanels(); });
	},
	bindToolbarButtonEvent: function() {	//	绑定工具栏按钮事件
		$(menuExit).click(function() {	//	退出登录
			window.mainpage.logout();
		});
		$(menuFullSreen).click(function () {	//	全屏支持
			if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)){	//	IE
				var wsh = new ActiveXObject('WScript.Shell');  
				wsh.sendKeys('{F11}'); 
			}
            if ($.util.supportsFullScreen) {
                if ($.util.isFullScreen()) {
                    $.util.cancelFullScreen();
                } else {
                    $.util.requestFullScreen();
                }
            } else {
            	$.messager.show({
            		title:'系统消息',
            		msg:'当前浏览器不支持全屏 API，请更换至最新的浏览器或通过 F11 快捷键进行操作。'
            	});
            }
        });
	},
	loadResources: function() {	//	加载资源菜单
		loadPage({id:'index-west-panel', url: 'application/resource', selector: 'appMenu', callback: function() {	
			$("#indexMaskContainer").remove();
		}});
	},
	logout: function() {	//	退出登录
		$.messager.confirm("操作提醒", "您确定要退出当前应用？", function (c) {
            if (c) {
            	sessionStorage.clear();	//	清空浏览器会话缓存
                emplmis.app.stop();	//	停止应用并跳转到登录页面
            }
        });
	},
	heartbeatWorker: null,
	hideNorth: function() {	//	隐藏北部面板
		$(mainLayout).layout('collapse', 'north');
	},
	hideWest: function() {	//	隐藏西部面板
		$(mainLayout).layout('collapse', 'west');
	},
	hideCenter: function() {	//	隐藏中间面板
		$(mainLayout).layout('collapse', 'center');
	},
	hideSouth: function() {	//	隐藏南部面板
		$(mainLayout).layout('collapse', 'south');
	},
	showNorth: function() {	//	展开北部面板
		$(mainLayout).layout('expand', 'north');
	},
	showWest: function() {	//	展开西部面板
		$(mainLayout).layout('expand', 'west');
	},
	showCenter: function() {	//	展开中间面板
		$(mainLayout).layout('expand', 'center');
	},
	showSouth: function() {	//	展开南部面板
		$(mainLayout).layout('expand', 'south');
	},
	togglePanels: function() {	//	折叠或者展开所有面板
		if(!this.isCollapse) {
			$(mainTabsToggleAllIcon).removeClass('fa-expand');
			$(mainTabsToggleAllIcon).addClass('fa-compress');
			this.hideNorth();
			this.hideWest();
			this.hideSouth();
			this.isCollapse = true;
		} else {
			$(mainTabsToggleAllIcon).removeClass('fa-compress');
			$(mainTabsToggleAllIcon).addClass('fa-expand');
			this.showNorth();
			this.showWest();
			this.showSouth();
			this.isCollapse = false;
		}
	},
};

var _indexMainTabs = window.mainpage.mainTabs = {	//	初始化标签栏
	addModule: function(title, href, iconCls, iniframe, closable, refreshable, selected) {	//	标签栏增加一个模块
		var opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
		var isExists = window.mainpage.mainTabs.isExists(opts.title, opts.href);
        switch (isExists) {
            case 0: window.mainpage.mainTabs.createTab(opts); break;
            case 1: window.mainpage.mainTabs.createTab(opts); break;
            case 2: window.mainpage.mainTabs.jumpTab(opts.title); break;
            default: break;
        }
	},
	createTab: function(title, href, iconCls, iniframe, closable, refreshable, selected, pre) {	//	创建一个tab
		var t = $(mainTabs), i = 0, opts = window.mainpage.mainTabs.parseCreateTabArgs(arguments);
        while (t.tabs("getTab", opts.title + (i ? String(i) : ""))) { i++; }
        t.tabs("add", {title:opts.title, url:opts.href, iconCls:opts.iconCls, iniframe:opts.iniframe, closable:opts.closable, refreshable:opts.refreshable, selected:opts.selected});
        loadPage({url: opts.href, selector: _appConfigs.appAjaxLoadFlag, callback: function(pageContent) {	//	加载页面
            if(pageContent != undefined && pageContent != "") {
            	t.tabs('getTab', opts.title).append(pageContent);
                $.parser.parse(t.tabs('getTab', opts.title));
            }
        }, asyncCallback: function() {	//	异步加载js回调函数处理
        	_indexMainTabs.preHandler(pre);
        }});
	},
	isExists: function(title, href) {	//	判断指定的选项卡是否存在于当前主页面的选项卡组中
		var t = $(mainTabs), tabs = t.tabs("tabs"), array = $.array.map(tabs, function (val) { return val.panel("options"); }),
        list = $.array.filter(array, function (val) { return val.title == title; }), ret = list.length ? 1 : 0;
        if (ret && $.array.some(list, function (val) { return val.url == href; })) { ret = 2; }
        return ret;
	},
	jumpTab: function(which, preHandler) {	//	tab跳转
		$(mainTabs).tabs("select", which);
		this.preHandler(preHandler);
	},
	parseCreateTabArgs: function(args) {	//	解析方法参数
		var ret = {};
        if (!args || !args.length) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption); //得到合并的结果却又不想修改ret的结构
        } else if (args.length == 1) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, typeof args[0] == "object" ? args[0] : { title: args[0] });
        } else if (args.length == 2) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1]});
        } else if (args.length == 3) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2] });
        } else if (args.length == 4) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3] });
        } else if (args.length == 5) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4] });
        } else if (args.length == 6) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5] });
        } else if (args.length >= 7) {
            $.extend(ret, window.mainpage.mainTabs.tabDefaultOption, { title: args[0], href: args[1], iconCls: args[2], iniframe: args[3], closable: args[4], refreshable: args[5], selected: args[6] });
        }
        return ret;
	},                                                                                    
	preHandler: function(preHandler) {	//	脚本预处理
		if(typeof preHandler == 'object' && preHandler.name) {
			var fn = eval(preHandler.name);
			if(typeof fn === 'function') {
				fn.call(this, preHandler.params);
			}
		}
	},
	tabDefaultOption: {	//	选项卡默认配置
		title: "新建选项卡", href: "", iniframe: true, closable: true, refreshable: true, repeatable: true, selected: true
	}
};

/**
 * 密码更新
 */
function pwdModifyFun(){
	$('#pwdModifyForm').form('submit',{
		url:'application/user/updatePassword',
		success: function(data){
			var resultData = $.parseJSON(data);
			if(resultData.success == 'true'){
				$.messager.show({
					title:'我的消息',
					msg:resultData.message,
					showType:'slide',
				});
			}else if(resultData.success == 'false'){
				$.messager.show({
					title:'我的消息',
					msg:resultData.message,
					showType:'slide',
				});
			}
			$('#pwdModify').dialog('close');
		}
	});
	
}

/**
 * 绑定字典表数据
 */
function getDicts() {
	var tableNames = "dict_education,dict_gender,dict_losetouchtime,dict_employestate,dict_knry,dict_difficultytype,dict_approvestate,dict_removereason,dict_street,dict_community";
	if(sessionStorage.forSpermData==undefined){
		$.ajax({
			url:'application/dict/getMultiDictDataByTableNames',
			type:'post',
			data:{
				tableNameSet:tableNames
			},
			success:function(data){
				sessionStorage.forSpermData = JSON.stringify(data);
				for(var j=0;j<data.length;j++){
					$.appCache.push(data[j].tableName,data[j].dictCommonDataList);
				}
				addFlag = true;
			}
		});
		
	}else{
		var forSpermDictData = $.parseJSON(sessionStorage.getItem('forSpermData'));
		for(var m=0;m<forSpermDictData.length;m++){
			$.appCache.push(forSpermDictData[m].tableName,forSpermDictData[m].dictCommonDataList);
		}
		addFlag = true;
	}
}

$.extend($.fn.validatebox.defaults.rules, {    
    equals: {    
        validator: function(value){   
        	var oldValue = $('#currentPwd').val();
        	return value != oldValue;
        },    
        message: '新密码不得与原密码相同'   
    },
    /**
     * 身份证号码位数验证
     */
    formatValid:{
  	  validator:function(value){
  		  var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
  		 return reg.test(value) != false;
  	  },
  	  message:'身份证号位数不正确！'
    },
    /**
     * 身份证号码出生年月日验证
     */
    idValid:{
  	  validator:function(value){
  		return idCardValid(value);
  	  },
  	  message:'请输入正确的身份证号'
  		  
    },
    phoneRex: {
        validator: function(value){
        	var rex=/^1[3-8]+\d{9}$/;
        	var rex2=/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
            if(rex.test(value)||rex2.test(value)){
            	return true;
            } else{
            	return false;
            }       
        },
        message: '请输入正确电话或手机格式'
      }
});
/**
* 校验日期
*/
function verifyBirthday(year,month,day,birthday) {
   var now = new Date();
   var now_year = now.getFullYear();
   //年月日是否合理
   if(birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day)
   {
       //判断年份的范围（0岁到100岁之间)
       var time = now_year - year;
       if(time >= 0 && time <= 100)
       {
           return true;
       }
       return false;
   }
   return false;
};
/**
* 身份证号码出生年月日验证函数
*/
function idCardValid(Card){
	  var len = Card.length;
	  if(len == '15')
	  {
	  var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
	  var arr_data = Card.match(re_fifteen);
	  var year = arr_data[2];
	  var month = arr_data[3];
	  var day = arr_data[4];
	  var birthday = new Date('19'+year+'/'+month+'/'+day);
	  return verifyBirthday('19'+year,month,day,birthday);
	  }
	  //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
	  if(len == '18')
	  {
		  var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
		  var arr_data = Card.match(re_eighteen);
		  if(arr_data==null){
			  return false;
		  }
		  var year = arr_data[2];
		  var month = arr_data[3];
		  var day = arr_data[4];
		  var birthday = new Date(year+'/'+month+'/'+day);
		  return verifyBirthday(year,month,day,birthday);
	  } 
	return false;
}

$(function(){
	$(".index-north-panel").prepend("<img src='./resources/images/app/app-top-header.jpg' id='topgpic'>");
	cover(); 
	$(window).resize(function(){  //浏览器窗口变化
		cover(); 		
	});
	
	function cover(){
		var window_w = $(window).width();
		//var div_h =$(".index-north-panel").height();
		$("#topgpic").attr({
			width:window_w,
			//height:div_h
			height:"65"
		});
	};
	
});



